/**
 * $Id: DbUnitUtils.java 8 2010-11-02 15:30:09Z feigme $
 */
package com.iary.core.test;

import javax.sql.DataSource;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceUtils;

public class DbUnitUtils {

	private static IDatabaseConnection getIconn(DataSource dataSource) throws Exception {
		return new DatabaseConnection(DataSourceUtils.getConnection(dataSource));
	}

	public static QueryDataSet getActual(DataSource dataSource, String tableName, String query) throws Exception {
		QueryDataSet actual = new QueryDataSet(getIconn(dataSource));
		actual.addTable(tableName, query);
		return actual;
	}

	public static IDataSet getExpected(String path) throws Exception {
		return new FlatXmlDataSetBuilder().build(new ClassPathResource(path).getFile());
	}

	public static void insert(DataSource dataSource, String... path) throws Exception {
		for (String xmlPath : path) {
			IDataSet data = new FlatXmlDataSetBuilder().build(new ClassPathResource(xmlPath).getFile());
			DatabaseOperation.INSERT.execute(getIconn(dataSource), data);
		}
	}

}
